package vn.ugame.module.store;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import vn.ugame.model.bl.Configuration;
import vn.ugame.model.bl.FindResult;
import vn.ugame.model.bl.ModuleManager;
import vn.ugame.model.bl.StoreService;
import vn.ugame.model.entity.*;
import vn.ugame.module.Module;
import vn.ugame.module.*;

public class StoreModule extends AbstractModule implements Module {

    public StoreModule() {
    }

    @ActionConfig(urlPattern = {"", "^(?<page>\\d+)/?$", "^(?<page>\\d+)/(?<keyword>[^/]+)/?$"})
    public void displayStore(@Param("keyword") String keyword, @Param("page") int page)
            throws ServletException, IOException {
        try {
            /**
             * Set default values for parameters
             */
            page = page <= 0 ? 1 : page;
            keyword = keyword != null && keyword.trim().equals("") ? null : keyword;

            /**
             * declare service
             */
            ModuleManager manager = new ModuleManager();
            StoreService service = new StoreService();

            /**
             * Prepare default model for store module
             */
            // Create default model
            List<vn.ugame.model.entity.Module> categories = manager.findLocalModules(ModuleType.STORE_SPECIFIC, getConfig().getLocale());
            List<vn.ugame.model.entity.Module> roots = manager.findRootModules(getConfig().getLocale());
            List<Language> languages = new ArrayList<Language>();
            List<vn.ugame.model.entity.Module> localModules = manager.findLocalModules(getConfig().getId());
            for (vn.ugame.model.entity.Module module : localModules) {
                vn.ugame.model.entity.Language language = new Language();
                if (module.getName().equals(getConfig().getName())) {
                    language.setCurrent(true);
                } else {
                    language.setCurrent(false);
                }
                language.setLocale(module.getLocale());
                language.setUrl("/" + module.getName() + "/" + getQueryString());
                languages.add(language);
            }
            List<vn.ugame.model.entity.Module> authModules = manager.findLocalModules(ModuleType.AUTH, getConfig().getLocale());
            vn.ugame.model.entity.Module loginModule = null;
            vn.ugame.model.entity.Module registerModule = null;
            for (vn.ugame.model.entity.Module module : authModules) {
                if (module.getDefaultName().equalsIgnoreCase("login")) {
                    loginModule = module;
                } else if (module.getDefaultName().equalsIgnoreCase("register")) {
                    registerModule = module;
                }
            }
            double rateOfCurrency = 0;
            try {
                rateOfCurrency = Double.parseDouble(Configuration.getInstance().getProperty(getConfig().getLocale(), "rate-of-currency"));
            } catch (NumberFormatException ex) {
                ex.printStackTrace();
            }
            //Save default model into request scope
            if (getRequest().getSession(true).getAttribute("message") != null) {
                getRequest().setAttribute("message", getRequest().getSession(true).getAttribute("message"));
                getRequest().getSession().removeAttribute("message");
            }
            getRequest().setAttribute("config", getConfig());
            getRequest().setAttribute("roots", roots);
            getRequest().setAttribute("categories", categories);
            getRequest().setAttribute("languages", languages);
            getRequest().setAttribute("loginModule", loginModule);
            getRequest().setAttribute("registerModule", registerModule);
            getRequest().setAttribute("rateOfCurrency", rateOfCurrency);

            /**
             * Prepare alternative model for display item action
             */
            // Create model
            FindResult<Item> model = null;
            List<Item> sliders = null;
            if (getConfig().getType() == ModuleType.STORE_ALL) {
                model = service.findItems(null, keyword, page, getConfig().getLocale());
                sliders = service.findSliderLocalItems(null, getConfig().getLocale(), ItemStatus.HOT, 5);
            } else if (getConfig().getType() == ModuleType.STORE_SPECIFIC) {
                model = service.findItems(getConfig().getId(), keyword, page, getConfig().getLocale());
                sliders = service.findSliderLocalItems(getConfig().getId(), getConfig().getLocale(), ItemStatus.HOT, 5);
            }
            //Save model into request scope
            getRequest().setAttribute("model", model);
            getRequest().setAttribute("sliders", sliders);

            /**
             * Forward model to view
             */
            RequestDispatcher dispatcher = getRequest().getRequestDispatcher("/store.jsp");
            dispatcher.forward(getRequest(), getResponse());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @ActionConfig(urlPattern = {"^(?<name>[a-zA-Z0-9_-]+)/(?<id>[a-zA-Z0-9_-]+)$"})
    public void displayItem(@Param("id") String id, @Param("name") String name)
            throws ServletException, IOException {
        try {
            /**
             * declare service
             */
            ModuleManager manager = new ModuleManager();
            StoreService service = new StoreService();

            /**
             * Prepare default model for store module
             */
            // Create default model
            List<vn.ugame.model.entity.Module> categories = manager.findLocalModules(ModuleType.STORE_SPECIFIC, getConfig().getLocale());
            List<vn.ugame.model.entity.Module> roots = manager.findRootModules(getConfig().getLocale());
            List<Language> languages = new ArrayList<Language>();
            List<Item> localItems = service.findLocalItems(id);
            for (Item localItem : localItems) {
                vn.ugame.model.entity.Language language = new Language();
                if (localItem.getName().equals(name)) {
                    language.setCurrent(true);
                } else {
                    language.setCurrent(false);
                }
                language.setLocale(localItem.getLocale());
                language.setUrl("/" + localItem.getModule().getName()
                        + "/" + localItem.getName() + "/" + localItem.getId());
                languages.add(language);
            }
            List<vn.ugame.model.entity.Module> authModules = manager.findLocalModules(ModuleType.AUTH, getConfig().getLocale());
            vn.ugame.model.entity.Module loginModule = null;
            vn.ugame.model.entity.Module registerModule = null;
            for (vn.ugame.model.entity.Module module : authModules) {
                if (module.getDefaultName().equalsIgnoreCase("login")) {
                    loginModule = module;
                } else {
                    registerModule = module;
                }
            }
            double rateOfCurrency = 0;
            try {
                rateOfCurrency = Double.parseDouble(Configuration.getInstance().getProperty(getConfig().getLocale(), "rate-of-currency"));
            } catch (NumberFormatException ex) {
                ex.printStackTrace();
            }
            //Save default model into request scope
            getRequest().setAttribute("config", getConfig());
            getRequest().setAttribute("roots", roots);
            getRequest().setAttribute("categories", categories);
            getRequest().setAttribute("languages", languages);
            getRequest().setAttribute("loginModule", loginModule);
            getRequest().setAttribute("registerModule", registerModule);
            getRequest().setAttribute("rateOfCurrency", rateOfCurrency);

            /**
             * Prepare alternative model for display item action
             */
            // Create model
            Item item = service.findLocalItem(getConfig().getId(), id, name);
            List<Item> relatedItems = service.findLocalRelatedItems(id, getConfig().getLocale());
            //Process item not found exception
            if (item == null) {
                getResponse().sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            List<Image> screenShots = service.findImage(id, ImageType.SCREEN_SHOT);
            //FindResult<Comment> comments = service.findComments(id, 1);

            //Save model into request scope
            getRequest().setAttribute("item", item);
            getRequest().setAttribute("relatedItems", relatedItems);
            getRequest().setAttribute("screenShots", screenShots);
            //getRequest().setAttribute("comments", comments);

            /**
             * Forward model to view
             */
            RequestDispatcher dispatcher = getRequest().getRequestDispatcher("/item.jsp");
            dispatcher.forward(getRequest(), getResponse());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
